import requests,base64,hashlib
import datetime
from time import strftime
import pymongo
import pandas as pd
import requests
df = pd.read_excel('/home/scrapy_config/jianbao.xlsx')
data_name=df['data_name'][0]
db_string=df['db'][0]

def fanyi(eestring):
    url = "http://192.168.50.101:8000/fanyi"
    # 需要注意的是Content-Length参数如果没有，data表单则不会随着请求被发送给服务端，且使用fiddler抓包的过程中，也无法看到data表单
    z="    "
    d ={'e':eestring,'z':z}
    result = requests.post(url,json=d)
    return result.content.decode('utf-8')
class WXWork_SMS:
    def __init__(self):
        self.headers = {"Content-Type": "text/html"}
        self.send_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1e514663-9629-4de0-b21b-cba275d680d7"  # 测试机器人webhook地址
        self.auth = ('Content-Type', 'application/json')


    def send_requests(self,send_data):
        res = requests.post(url=self.send_url, headers=self.headers, json=send_data, auth=self.auth)
        print(res.json())
        
    def send_msg(self,msg):
        # 发送消息
        send_data = {
            "msgtype": "text",  # 消息类型，此时固定为news
            "text": {
                "content": msg,
                "mentioned_list":  ["@all"]
            }
        }
        self.send_requests(send_data)
if __name__ == '__main__':
    sms = WXWork_SMS()
    ip ='192.168.50.101'
    port='27017'
    client = pymongo.MongoClient('mongodb://'+str(ip)+":"+str(port)+"/")
    db_dhs=client[db_string]
    now=datetime.datetime.now()
    yes = now + datetime.timedelta(days = -1)
    lastcollectionname =  "co"+yes.strftime('%Y%m%d')+"co"
    collectionname = "co"+now.strftime("%Y%m%d")+"co"
    collectionname_yikan= "kn"+now.strftime("%Y%m%d")+"kn"
    collection_dhs = db_dhs[collectionname]
    collection_dhs_last = db_dhs[lastcollectionname]
    collection_dhs_yikan = db_dhs[collectionname_yikan]
    collection_dhs_yikan.insert_one({"title":"ddd"})
    data_all = collection_dhs.find()
    mee=[]
    msg='               '+data_name+'            \n'+"-----------\n"+now.strftime("%Y%m%d %H:%M:%S")+"\n"
    i=0
    tmp=0
    for data_one in data_all:
        cont =False
        trans = data_one.get('trans')
        title = data_one.get('title')
        content = data_one.get('content')
        url =  data_one.get('url')
        if (collection_dhs_last.count_documents({'title':title})!=0) or(collection_dhs_yikan.count_documents({'title':title})!=0):
                #print(title)
                cont =True
                #print('已重复')
        if cont ==False:
            print('不重复')
            print(title)
            collection_dhs_yikan.update_one({'title': str(title)}, {'$set': data_one}, True)
            if trans =="yes":
                if (not title    is None)  and (not len(title) ==0):
                    title = fanyi(title)
                if (not content    is None)  and (not len(content) ==0):
                    content = fanyi(content)
            stringone =str(title)+"\n"+str(content)+"\n"+str(url)+"\n"
            msg=msg+stringone
            i=i+1
            if i >=20:
                tmp=tmp+i
                i=0
                mee.append(msg)
                msg=''
            print(msg)
            print(mee)
    tail ="共计"+str(tmp)+"条"
    if tmp==0:
        tail ="共计"+str(i)+"条"    
    if msg !='               '+data_name+'            \n'+"-----------\n"+now.strftime("%Y%m%d %H:%M:%S")+"\n":
        mee.append(msg)
    if not (len(mee)==0):
        msg_tail = mee.pop()
        msg_tail=msg_tail+tail
        mee.append(msg_tail)
    for me  in mee:
        sms.send_msg(me)